package cn.kmsoft.spatialboot.service.executor;

import cn.kmsoft.wololo.object.GeoJson;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.kmsoft.spatialboot.common.object.TaskParam;
import cn.kmsoft.spatialboot.common.object.TaskResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * @author
 * @date
 */
//s@Slf4j
public abstract class BaseParallelExecutor {
    private static final Logger logger = LoggerFactory.getLogger(BaseParallelExecutor.class);

    /**
     * 以多线程的方式执行任务
     *
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public GeoJson[] executeTask(TaskParam param, String geoJson) throws InterruptedException, ExecutionException {
        JSONArray inputFeatures = JSONObject.parseObject(geoJson).getJSONArray("features");
        int threadNum = 5;
        if (inputFeatures.size() <= threadNum) {
            threadNum = inputFeatures.size();
        }

        GeoJson[] outGeoJson = new GeoJson[inputFeatures.size()];
        if (threadNum > 1) {
            //region 多线程
            //log.info("线程数：{}", threadNum);
            logger.info("线程数：{}", threadNum);

            ExecutorService exec = Executors.newFixedThreadPool(threadNum);
            CompletionService<TaskResult> completionService = new ExecutorCompletionService<>(exec);
            try {
                //以地块为单位，多线程提交任务
                for (int i = 0; i < inputFeatures.size(); i++) {
                    final JSONObject inputFeature = inputFeatures.getJSONObject(i);
                    final int index = i;
                    //DifferenceExecutor->task(index, param, inputFeature);
                    completionService.submit(() -> task(index, param, inputFeature));
                }
                long begin = System.currentTimeMillis();
                // 输出结果
                for (int i = 0; i < inputFeatures.size(); i++) {
                    //等待，接收多线程的分析结果
                    TaskResult taskResult = completionService.take().get();
                    GeoJson json = new GeoJson();
                    json.setType("FeatureCollection");
                    json.setFeatures(taskResult.getFeatures());

                    outGeoJson[taskResult.getIndex()] = json;
                }

                logger.info("处理线程请求结果耗时：{}", (System.currentTimeMillis() - begin));
                logger.info("executeTask结果：{}", (outGeoJson.length));
            } finally {
                exec.shutdown();
            }
            // endregion
        } else {
            TaskResult taskResult = task(0, param, inputFeatures.getJSONObject(0));
            GeoJson json = new GeoJson();
            json.setType("FeatureCollection");
            json.setFeatures(taskResult.getFeatures());
            outGeoJson[taskResult.getIndex()] = json;
        }

        return outGeoJson;
    }

    /**
     * 实际获取信息的任务
     *
     * @param geometry
     * @return
     */
    protected abstract TaskResult task(int index, TaskParam param, JSONObject geometry);
}
